<template>
  <view class="spike">
    <view class="timer" v-if="times.length > 0">
      <scroll-view scroll-x class="scroll-box">
        <view class="timer-box">
          <block v-for="time in times">
          <view :class="{'item': true,  'active':time.seckillId === seckill_id}" :key="time.seckillId" >
            <view class="align-center" @click="seckill_id= time.seckillId">
              <view class="time">{{`${time.start_hour}:${time.start_minute}`}}</view>
              <view class="tag ing" v-if="time.state" >进行中</view>
              <view class="tag ing" v-else>即将开抢</view>
            </view>
          </view>
          </block>
        </view>
      </scroll-view>
      <view class="second">
<!--        距结束 00:23:23-->
        {{timeLeft}}
      </view>
    </view>
    <view class="empty" v-else>
      暂时没有秒杀活动
    </view>

    <block v-if="times.length>0">
      <GoodsGroup
          ref="goodsgroup"
        :requestData="getGoodsList"
        @success="handleSuccess"
        @error="handleError"
        :limit="10"
        :total="total"
        :page="goodsPage"
      >
        <template  v-for="goods in goodsList">
        <GoodsItem
            :keys="goods.goods_id"
            :id="goods.goods_id"
            :name="goods.goods_name"
            :cover="goods.goods_image"
            :price="goods.seckill_price"
            :state = "goodsState"
            :stock="9999"
            @click="toDetail(goods.goods_id)"
        />
        </template>

    </GoodsGroup>
    </block>
  </view>
</template>
<script>
import GoodsGroup from '@/components/gm-goods/group.vue';
import GoodsItem from '@/components/gm-goods/spikeGoods.vue';
export default {
  components:{
    GoodsGroup,
    GoodsItem
  },
  data(){
    return{
      goodsList: [],
      goodsPage: 1,
      maxPage: 5,
      times:[],
      seckill_id: '', // 当前秒杀
      timeLeft: '距开始 00:00:00',
      clearTime:null,
      total: 0,
    }
  },
  created(){
    this.getTheNumberOfSpikes();
  },
  // 底部加载
  onReachBottom(){
    console.log('加载底部');
    this.goodsPage += 1;
  },
  destroy(){
    clearInterval(this.clearTime)
  },
  computed:{
    goodsState(){
      let time;
      this.times.some(item=>{
        if (item.seckillId === this.seckill_id){
          time = item;
          return true;
        }
        return false;
      })
      if (time){
        let {processing} = this.isItInProgress(time);
        return processing;
      }

      return false;
    }
  },
  watch:{
     seckill_id(){

      this.goodsList = [];
      this.total = 0;
      this.goodsPage = 1;
      this.getCountdown()
      this.$nextTick(()=>{
        this.$refs.goodsgroup.handleRequestData(true)
      })
    }
  },
  methods:{
    toDetail(id){
      uni.navigateTo({
        url:`/pages/product/product_seckill?id=${id}&time_id=${this.seckill_id}`,
        fail:(error)=>{
          console.log(error);
        }
      })
    },
    // 获取倒计时
    getCountdown(){
      let time;
      this.times.some(item=>{
       if (item.seckillId === this.seckill_id){
         time = item;
         return true;
       }
        return false;
      })

      if (this.clearTime){
        clearInterval(this.clearTime)
      }


      this.clearTime = setInterval(()=>{
        let timeStr = '';
        if (time){
          let {startTime, endTime, currentTime, processing} = this.isItInProgress(time);
          if (processing){
            // 时 分 秒
            let surplus = Math.abs(endTime - currentTime)/ 1000;
            // 时
            timeStr += '距结束 '+this.getTimeDown(surplus)
          }else{
            let surplus = Math.abs(startTime - currentTime)/ 1000;
            // console.log(startTime);
            timeStr += '距开始 ' +this.getTimeDown(surplus)
          }
        }
        this.timeLeft = timeStr;

      }, 1000)

    },
    // 时间换算
    getTimeDown(surplus){
      // 时
      let hours =0, minute = 0 , second =0;
      if (surplus >= 3600){
        hours = Math.floor(surplus / 3600);
        // console.log('surplus / 3600========', (surplus / 3600));
        surplus -= hours*(3600);
      }
      if (surplus >= 60){
        minute = Math.floor(surplus / 60);
        second = surplus - minute*60;
      }else{
        second = surplus;
      }
      second = second.toFixed(0);
      if (second <= 0  && surplus <= 0){
        this.switchSeckillId();
      }

      return (hours >= 10 ? hours : `0${hours}`)+':'+(minute >= 10 ? minute : `0${minute}`)+':'+(second >= 10 ? second : `0${second}`);
    },
    isItInProgress(time){
      const {start_time, end_time} = time;
      let date = new Date();
      let today = date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate();
      let startTime = Date.parse(`${today} ${start_time}`)
      let endTime = Date.parse(`${today} ${end_time}`)
      console.log(date);

      let currentTime = Date.now();
      let processing = false;
      if (startTime <= currentTime && currentTime < endTime){
        processing = true;
      }

      return {
        startTime,
        endTime,
        currentTime,
        processing
      };
    },
    switchSeckillId(){
      this.times = this.times.map(time=>{
        time.state = false;
        if (this.isItInProgress(time)['processing']){
          time.state = true;
          this.seckill_id = time.seckillId;
        }

        return time;
      })

      if (!this.seckill_id){
        this.seckill_id =this.times[0].seckillId;
      }
    },
    // 获取场次
    getTheNumberOfSpikes(){
      this.$Request.request('/api/seckill/getSeckillTime', 'GET').then(res => {
        console.log(res)
        const {status, data:{list}} = res;
        this.times = list
        if (status === 1) {
          // 赋值当前场次 seckill_id
          this.switchSeckillId();
        } else {
          this.$api.msg('获取秒杀出现异常')
          uni.navigateBack()
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 获取商品接口
    getGoodsList(params){
      return this.$Request.request('/api/seckill/getSeckillGoods?seckill_id='+this.seckill_id, 'GET', params)
    },
    // 请求接口成功返回数据
    handleSuccess(result){
      const {data:{data, total}, msg, status} = result;
      this.total = total
      if (status === 1){
        this.goodsList = this.goodsList.concat(data);
      }
      console.log(this.goodsList);
    },
    // 失败
    handleError(error) {
      uni.showToast({
        title: error || '数据异常',
        icon: 'none'
      })
    }
  }
}

</script>
<style lang="scss">

.spike{
  background: $themColor;
  display: block;
  min-height: 95vh;
  height: 100%;
  padding: 26rpx;
  box-sizing: border-box;

  .empty{
    color: white;
    text-align: center;
  }
  .timer{
    width: 100%;
    height: 232rpx;

    .timer-box{
      overflow: auto;
      white-space: nowrap;
      margin-top: 20rpx;
      padding: 10rpx 0rpx;

      .active{
        background: #FFFFFF;
        color: $themColor!important;
        .time{
          color: $themColor;
        }
        .tag{
          color: $themColor;
        }
      }
      .item{
        display: inline-block;
        //width: 30%;
        width: 190rpx; // 750-570 = 180-52= 128/2= 64
        margin-right: 64rpx;
        height: 98rpx;
        //line-height: 98rpx;
        border-radius: 10rpx;
        color: #ffffff;
        .time{
          width: 98rpx;
          font-size: 36rpx;
          font-weight: 600;
          margin: 0 auto;
          text-align: center;
        }
        .tag{
          width: 100%;
          text-align: center;
          font-size: 24rpx;
          font-weight: 600;
        }
      }
    }
    .align-center{
      margin: 8rpx 0rpx;
    }

    .second{
      margin: 10rpx auto;
      text-align: center;
      width: 342rpx;
      height: 52rpx;
      line-height: 52rpx;
      background: rgba(225,225,225, .4);
      border-radius: 26rpx;
      font-size: 26rpx;
      color: white;
    }
  }

}
</style>
